import 'package:bwt_ad_flutter/ad/BwtAd.dart';
import 'package:bwt_ad_flutter/manager/BwtAdManager.dart';

import '../../util/UuidUtil.dart';

abstract class BwtAdLoader<T extends BwtAd> {
  final String _adLoaderId = UuidUtil.uuid();
  final List<T> _adList = [];

  OnBwtAdEvent<T>? onAdLoad;
  OnBwtAdFailed<String>? onAdFailed;
  OnBwtAdEvent<T>? onAdExpose;
  OnBwtAdEvent<T>? onAdClick;
  OnBwtAdEvent<T>? onAdClose;

  String get adLoaderId => _adLoaderId;

  List<T> get adList => _adList;

  /// 加载广告
  load({
    required String posId,
    required String methodName,
    Map<String, dynamic>? arguments,
  }) {
    BwtAdManager.loadAd(
      bwtLoader: this,
      posId: posId,
      methodName: methodName,
      arguments: arguments,
    );
  }

  /// 广告加载成功回调
  onAdLoadCallback(T bwtAd) {
    onAdLoad?.call(bwtAd);
  }

  /// 广告加载失败回调
  onAdFailedCallback(String? error) {
    onAdFailed?.call(error ?? '');
  }

  /// 广告曝光回调
  onAdExposeCallback(T bwtAd) {
    onAdExpose?.call(bwtAd);
  }

  /// 广告被点击回调
  onAdClickCallback(T bwtAd) {
    onAdClick?.call(bwtAd);
  }

  /// 广告被关闭回调
  onAdCloseCallback(T bwtAd) {
    onAdClose?.call(bwtAd);
  }

  /// 释放广告
  release() {
    BwtAdManager.releaseAdLoader(bwtLoader: this);
  }

  /// 根据adId找到广告对象
  T? findBwtAd({required String? adId}) {
    if (adId == null) return null;
    for (var bwtAd in _adList) {
      if (bwtAd.adId == adId) return bwtAd;
    }
    return null;
  }

  /// 创建广告
  T createBwtAd({
    required String adId,
    required Map<String, dynamic>? arguments,
  });
}

typedef OnBwtAdEvent<T extends BwtAd> = void Function(T bwtAd);
typedef OnBwtAdFailed<String> = void Function(String error);
